<template>
  <div class="message-container">
    <div class="page-header">
      <h1>留言簿</h1>
    </div>

    <!-- 筛选条件卡片 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" ref="filterFormRef">
        <!-- 时间区间 -->
        <el-form-item label="时间区间" prop="dateRange">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>

        <!-- 发件人姓名 -->
        <el-form-item label="发件人" prop="senderName">
          <el-input
            v-model="filterForm.senderName"
            placeholder="请输入发件人姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <!-- 收件人姓名 -->
        <el-form-item label="收件人" prop="receiverName">
          <el-input
            v-model="filterForm.receiverName"
            placeholder="请输入收件人姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>

        <!-- 只看未读 -->
        <el-form-item>
          <el-checkbox
            v-model="filterForm.onlyUnread"
            label="只看未读"
          />
        </el-form-item>

        <!-- 查询按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 留言列表卡片 -->
    <el-card class="message-list-card" v-loading="listLoading">
      <el-table
        :data="messageList"
        border
        stripe
        style="width: 100%"
      >
        <!-- 留言方向（发送/接收） -->
        <el-table-column label="方向" width="100">
          <template #default="scope">
            <el-icon :color="scope.row.message_direction === 'send' ? '#409eff' : '#10b981'">
              <DArrowRight v-if="scope.row.message_direction === 'send'" />
              <DArrowLeft v-if="scope.row.message_direction === 'receive'" />
            </el-icon>
            <span class="direction-text">
              {{ scope.row.message_direction === 'send' ? '发送' : '接收' }}
            </span>
          </template>
        </el-table-column>

        <!-- 发件人姓名 -->
        <el-table-column prop="sender_name" label="发件人" width="120" />

        <!-- 收件人姓名 -->
        <el-table-column prop="receiver_name" label="收件人" width="120" />

        <!-- 内容预览 -->
        <el-table-column prop="content_preview" label="内容预览" min-width="200">
          <template #default="scope">
            <div class="content-preview" :title="scope.row.content_preview">
              {{ scope.row.content_preview }}
            </div>
          </template>
        </el-table-column>

        <!-- 发送时间 -->
        <el-table-column prop="send_time" label="发送时间" width="180" sortable />

        <!-- 是否已读 -->
        <el-table-column label="已读状态" width="120">
          <template #default="scope">
            <el-tag
              :type="scope.row.is_read ? 'success' : 'warning'"
              size="small"
            >
              {{ getReadStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 回复已读状态 -->
        <el-table-column label="回复状态" width="120">
          <template #default="scope">
            <template v-if="scope.row.is_read">
              <el-tag
                :type="scope.row.all_replies_read ? 'success' : 'warning'"
                size="small"
              >
                {{ scope.row.all_replies_read ? '全部已读' : '有未读回复' }}
              </el-tag>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 操作区域 -->
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(scope.row.id)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
        />
      </div>
    </el-card>

    <!-- 发送留言卡片 -->
    <el-card class="send-message-card">
      <h3>发送新留言</h3>
      
      <!-- 收件人选择区域 -->
      <div class="receiver-selector">
        <el-input
          v-model="receiverNames"
          placeholder="请选择收件人"
          readonly
          class="receiver-input"
        />
        <el-button type="primary" @click="openReceiverDialog">选择收件人</el-button>
      </div>

      <!-- 已选收件人标签 -->
      <div class="selected-receivers" v-if="selectedReceivers.length">
        <el-tag
          v-for="receiver in selectedReceivers"
          :key="receiver.id"
          closable
          @close="removeReceiver(receiver.id)"
          class="receiver-tag"
        >
          {{ receiver.name }}
        </el-tag>
      </div>

      <!-- 留言内容输入 -->
      <div class="message-input-area">
        <el-input
          v-model="messageContent"
          type="textarea"
          :rows="4"
          placeholder="请输入留言内容..."
          class="content-input"
        />
        <el-button
          type="primary"
          @click="handleSendMessage"
          :loading="sendLoading"
          :disabled="!selectedReceivers.length || !messageContent.trim()"
          class="send-button"
        >
          发送留言
        </el-button>
      </div>
    </el-card>
  </div>

    <!-- 收件人选择对话框 -->
    <el-dialog
      v-model="receiverDialogVisible"
      :title="isStudent ? '选择教师' : '选择学生'"
      width="600px"
      :close-on-click-modal="false"
    >
      <!-- 学生筛选条件（管理员/教师视角） -->
      <el-form
        :inline="true"
        :model="receiverFilterForm"
        ref="receiverFilterRef"
        v-if="!isStudent"
        class="receiver-filter-form"
      >
        <el-form-item label="班级">
          <el-select
            v-model="receiverFilterForm.classId"
            placeholder="请选择班级"
            clearable
            @change="fetchReceivers"
            style="width: 120px;"
          >
            <el-option
              v-for="cls in classList"
              :key="cls.id"
              :label="`${cls.grade}年级${cls.name}`"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input
            v-model="receiverFilterForm.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="fetchReceivers"
            style="width: 100px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchReceivers">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 收件人列表 -->
      <el-table
        ref="receiverTableRef"
        :data="receiverList"
        border
        stripe
        v-loading="receiverLoading"
        class="receiver-table"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="name"
          label="姓名"
          width="120"
        />
        <!-- 教师列表特有列 -->
        <el-table-column
          prop="subject"
          label="教授课程"
          v-if="isStudent"
        />
        <!-- 学生列表特有列 -->
        <el-table-column
          prop="className"
          label="班级"
          v-if="!isStudent"
        />
        <el-table-column
          prop="student_number"
          label="学号"
          v-if="!isStudent"
          width="100"
        />
      </el-table>

      <template #footer>
        <el-button @click="receiverDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReceivers">确认选择</el-button>
      </template>
    </el-dialog>

  <!-- 留言详情对话框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="留言详情"
    :width="600"
    :close-on-click-modal="false"
    @close="resetDetailForm"
  >
    <!-- 留言内容区域（带滚动条） -->
    <div class="message-detail-container" ref="messageContainerRef">
      <!-- 主留言 -->
      <div 
        class="message-item"
        :class="mainMessage.message_direction === 'send' ? 'send-message' : 'receive-message'"
      >
        <div class="sender-name">
          {{ mainMessage.sender_name }}
        </div>
        <div class="message-content">
          {{ mainMessage.content }}
        </div>
        <div class="message-time">
          {{ formatTime(mainMessage.send_time) }}
          <span v-if="!mainMessage.is_read" class="unread-tag">
            未读
          </span>
        </div>
      </div>

      <!-- 回复列表 -->
      <div class="replies-container">
        <div 
          v-for="reply in replies" 
          :key="reply.id"
          class="message-item"
          :class="reply.message_direction === 'send' ? 'send-message' : 'receive-message'"
        >
          <div class="sender-name">
            {{ reply.sender_name }}
          </div>
          <div class="message-content">
            {{ reply.content }}
          </div>
          <div class="message-time">
            {{ formatTime(reply.send_time) }}
            <span v-if="!reply.is_read" class="unread-tag">
              未读
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 回复输入区域（固定在底部） -->
    <div class="reply-input-container">
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="3"
        placeholder="请输入回复内容..."
        @keyup.enter="handleReply"
      />
      <div class="reply-button">
        <el-button 
          type="primary" 
          @click="handleReply"
          :loading="replyLoading"
          :disabled="!replyContent.trim()"
        >
          回复
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage, ElForm, ElTable } from 'element-plus';
import { DArrowRight, DArrowLeft } from '@element-plus/icons-vue';
import { getMessageDetail, getMessageList, replyMessage, sendMessage, type GetMessageDetailParams, type GetMessageListParams, type MessageItem, type ReplyMessageParams } from '../../api/message';
import { useAuthStore } from '../../store/authStore';
import { listClasses, type ClassItem } from '../../api/classmgr';
import { listTeachers, type TeacherItem } from '../../api/teachermgr';
import { listStudents, type StudentItem } from '../../api/studentmgr';

// 用户权限判断（仅管理员和教师显示班级筛选）
const authStore = useAuthStore();
const userRole = computed(() => authStore.user?.role);
const isStudent = computed(() => {
  return userRole.value === 'student';
});

// 状态管理
const listLoading = ref(false);
const messageList = ref<MessageItem[]>([]);
const filterFormRef = ref<InstanceType<typeof ElForm>>();

// 筛选表单数据
const filterForm = reactive({
  dateRange: ['', ''] as [string, string],
  senderName: '',
  receiverName: '',
  onlyUnread: false
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 页面初始化时加载数据
onMounted(async() => {
  await fetchMessageList();
  if (!isStudent.value) {
    await fetchClasses();
  }
});

// 格式化已读状态文本
const getReadStatusText = (message: MessageItem) => {
  if (message.message_direction === 'send') {
    return message.is_read ? '对方已读' : '对方未读';
  } else {
    return message.is_read ? '已读' : '未读';
  }
};

// 构建查询参数
const buildQueryParams = (): GetMessageListParams => {
  const [start_time, end_time] = filterForm.dateRange ?? [undefined, undefined];
  return {
    offset: (pagination.currentPage - 1) * pagination.pageSize,
    limit: pagination.pageSize,
    sender_name: filterForm.senderName || undefined,
    receiver_name: filterForm.receiverName || undefined,
    start_time: start_time || undefined,
    end_time: end_time || undefined,
    only_unread: filterForm.onlyUnread
  };
};

// 获取留言列表
const fetchMessageList = async () => {
  try {
    listLoading.value = true;
    const params = buildQueryParams();
    const res = await getMessageList(params);
    
    if (res.code === 200) {
      messageList.value = res.content.messages;
      pagination.total = res.content.total;
    } else {
      ElMessage.error(res.msg || '获取留言列表失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取留言列表异常');
  } finally {
    listLoading.value = false;
  }
};

// 搜索按钮点击
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchMessageList();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.dateRange = ['', ''];
  filterForm.senderName = '';
  filterForm.receiverName = '';
  filterForm.onlyUnread = false;
  pagination.currentPage = 1;
  fetchMessageList();
};

// 分页大小变化
const handlePageSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchMessageList();
};

// 页码变化
const handleCurrentPageChange = (page: number) => {
  pagination.currentPage = page;
  fetchMessageList();
};

// 详情对话框相关变量
const detailDialogVisible = ref(false);
const currentMessageId = ref(0);
const mainMessage = ref<any>({});
const replies = ref<any[]>([]);
const replyContent = ref('');
const replyLoading = ref(false);
const detailLoading = ref(false);
const messageContainerRef = ref<HTMLDivElement | null>(null);

// 打开详情对话框
const handleViewDetail = async (messageId: number) => {
  currentMessageId.value = messageId;
  detailDialogVisible.value = true;
  await fetchMessageDetail();
};

// 滚动到最底部的方法
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainerRef.value) {
      // 强制滚动到底部
      messageContainerRef.value.scrollTop = messageContainerRef.value.scrollHeight;
    }
  });
};

// 获取留言详情
const fetchMessageDetail = async () => {
  try {
    detailLoading.value = true;
    const params: GetMessageDetailParams = {
      message_id: currentMessageId.value
    };
    const res = await getMessageDetail(params);
    
    if (res.code === 200) {
      mainMessage.value = res.content.main_message;
      replies.value = res.content.replies;
      
      // 滚动到底部
      scrollToBottom();

      // 刷新留言列表更新已读状态
      await fetchMessageList();
    } else {
      ElMessage.error(res.msg || '获取留言详情失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取留言详情异常');
  } finally {
    detailLoading.value = false;
  }
};

// 回复留言
const handleReply = async () => {
  if (!replyContent.value.trim()) return;
  
  try {
    replyLoading.value = true;
    const params: ReplyMessageParams = {
      message_id: currentMessageId.value,
      content: replyContent.value.trim()
    };
    
    const res = await replyMessage(params);
    if (res.code === 200) {
      ElMessage.success('回复成功');
      replyContent.value = '';
      // 刷新详情
      await fetchMessageDetail();
      // 刷新留言列表更新已读状态
      await fetchMessageList();
    } else {
      ElMessage.error(res.msg || '回复失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '回复异常');
  } finally {
    replyLoading.value = false;
  }
};

// 格式化时间显示
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 重置详情表单
const resetDetailForm = () => {
  replyContent.value = '';
  mainMessage.value = {};
  replies.value = [];
  currentMessageId.value = 0;
};

// 收件人选择
const receiverDialogVisible = ref(false);
const selectedReceivers = ref<Array<{ id: number; name: string }>>([]);
const receiverNames = ref(''); // 用于显示已选收件人（只读输入框）
const receiverList = ref<any[]>([]);
const receiverLoading = ref(false);
const receiverFilterForm = reactive({
  classId: undefined,
  name: ''
});
const receiverFilterRef = ref<InstanceType<typeof ElForm>>();
const classList = ref<ClassItem[]>([]);

// 留言内容
const messageContent = ref('');
const sendLoading = ref(false);

// 获取班级列表（供筛选学生用）
const fetchClasses = async () => {
  try {
    const res = await listClasses();
    if (res.code === 200) {
      classList.value = res.content;
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取班级列表失败');
  }
};

// 获取收件人列表（教师或学生）
const fetchReceivers = async () => {
  try {
    receiverLoading.value = true;
    if (isStudent.value) {
      // 学生视角：获取教师列表
      const res = await listTeachers({ class_id: undefined, name: undefined });
      if (res.code === 200) {
        receiverList.value = res.content.map((teacher: TeacherItem) => ({
          id: teacher.teacher_id,
          name: teacher.teacher_name,
          subject: teacher.subject
        }));
      }
    } else {
      // 管理员/教师视角：获取学生列表
      const res = await listStudents({
        class_id: receiverFilterForm.classId,
        name: receiverFilterForm.name
      });
      if (res.code === 200) {
        receiverList.value = res.content.map((student: StudentItem) => ({
          id: student.student_id,
          name: student.name,
          student_number: student.student_number,
          className: `${student.grade}年级${student.class_name}`
        }));
      }
    }
  } catch (error: any) {
    ElMessage.error(error.message || '获取收件人列表失败');
  } finally {
    receiverLoading.value = false;
  }
};

// 打开收件人选择对话框
const openReceiverDialog = async () => {
  receiverDialogVisible.value = true;
  await fetchReceivers();
};

// 定义收件人表格 ref 引用
const receiverTableRef = ref<InstanceType<typeof ElTable> | null>(null);

// 确认选择收件人
const confirmReceivers = () => {
  // 通过 ref 获取表格实例，再调用 getSelectionRows 方法
  if (!receiverTableRef.value) return;
  
  const selectedRows = receiverTableRef.value.getSelectionRows();
  if (selectedRows.length === 0) {
    ElMessage.warning('请至少选择一个收件人');
    return;
  }

  // 保存选中的收件人
  selectedReceivers.value = selectedRows.map((row: any) => ({
    id: row.id,
    name: row.name
  }));
  
  // 更新显示文本（只读输入框）
  receiverNames.value = selectedReceivers.value.map(r => r.name).join('; ');
  receiverDialogVisible.value = false;
};

// 移除收件人
const removeReceiver = (id: number) => {
  selectedReceivers.value = selectedReceivers.value.filter(r => r.id !== id);
  receiverNames.value = selectedReceivers.value.map(r => r.name).join('; ');
};

// 发送留言
const handleSendMessage = async () => {
  if (selectedReceivers.value.length === 0) {
    ElMessage.warning('请选择收件人');
    return;
  }
  if (!messageContent.value.trim()) {
    ElMessage.warning('请输入留言内容');
    return;
  }

  try {
    sendLoading.value = true;
    const params = {
      receiver_ids: selectedReceivers.value.map(r => r.id),
      content: messageContent.value.trim()
    };

    const res = await sendMessage(params);
    if (res.code === 200) {
      ElMessage.success('留言发送成功');
      // 重置表单
      selectedReceivers.value = [];
      receiverNames.value = '';
      messageContent.value = '';
      // 刷新留言列表
      await fetchMessageList();
    } else {
      ElMessage.error(res.msg || '发送失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '发送异常');
  } finally {
    sendLoading.value = false;
  }
};
</script>

<style scoped>
.message-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.message-list-card {
  padding: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.direction-text {
  margin-left: 5px;
  font-size: 14px;
}

.content-preview {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 详情对话框样式 */
.message-detail-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
  margin-bottom: 15px;
}

.message-item {
  margin-bottom: 15px;
  padding: 0 10px;
}

.send-message {
  text-align: left;
}

.receive-message {
  text-align: right;
}

.sender-name {
  font-size: 12px;
  margin-bottom: 5px;
  color: #606266;
}

.message-content {
  display: inline-block;
  max-width: 70%;
  padding: 8px 12px;
  border-radius: 6px;
  word-break: break-word;
}

.send-message .message-content {
  background-color: #e6f4ff;
  color: #303133;
}

.receive-message .message-content {
  background-color: #f0f9eb;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.unread-tag {
  color: #f56c6c;
  margin-left: 5px;
  font-size: 12px;
}

.replies-container {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #e5e7eb;
}

.reply-input-container {
  border-top: 1px solid #e5e7eb;
  padding-top: 15px;
}

.reply-button {
  margin-top: 10px;
  text-align: right;
}

/* 发送留言卡片样式 */
.send-message-card {
  margin-top: 20px;
  padding: 20px;
}

.send-message-card h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.receiver-selector {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: center;
}

.receiver-input {
  flex: 1;
}

.selected-receivers {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.receiver-tag {
  cursor: pointer;
}

.message-input-area {
  margin-top: 15px;
}

.content-input {
  margin-bottom: 10px;
}

.send-button {
  float: right;
}

/* 收件人选择对话框样式 */
.receiver-filter-form {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e5e7eb;
}

.receiver-table {
  width: 100%;
}
</style>